package com.lxy.dataservice.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.lxy.dataservice.constants.MessageConstants;
import com.lxy.dataservice.dao.DurgDao;
import com.lxy.dataservice.dao.SoldNoteDao;
import com.lxy.dataservice.entity.Durg;
import com.lxy.dataservice.entity.SoldNote;
import com.nip.db.mongodb.utils.tips.Response;
import com.nip.db.mongodb.utils.tips.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * DurgService
 *
 * @author < a href=" ">BBB</ a>
 * @version v1.0.01
 * @date 2019-12-26 15:43
 */
@Service
public class DurgService {
  @Autowired
  DurgDao durgDao;
  @Autowired
  SoldNoteDao soldNoteDao;

  /**
   * 保存药品
   */
  public Response saveDurg(Durg entity) {
    try {
      durgDao.save(entity);
      return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
    } catch (Exception e) {
      return new Response(ResponseCode.CODE_202, e.getMessage());
    }
  }

  /**
   * 修改药品同时往销量表存数据
   */
  public Response updateDurg(Durg entity) {
    try {
      Durg durg = durgDao.findById(entity.getId()).orElse(new Durg());
      if (durg.getStock()-entity.getStock()!= 0){
        SoldNote soldNote = new SoldNote();
        soldNote.setUpdateTime(DateUtil.now());
        soldNote.setDurgsId(entity.getId());
        soldNote.setSaleNumber(durg.getStock()-entity.getStock());
        soldNoteDao.save(soldNote);
      }
      durgDao.save(entity);
      return new Response(ResponseCode.CODE_200,MessageConstants.SUCCESS);
    }catch (Exception e){
      return new Response(ResponseCode.CODE_202,e.getMessage());
    }
  }


  /**
   * 根据药品类别id查药品
   */
    public List<Durg> findDurgByTypeId(String id) {
    if (StrUtil.isEmpty(id)){
      return durgDao.findAll();
    }else {
      return durgDao.findByTypeId(id);
    }
  }

  /**
   * 根据id查药品
   */
    public Durg findDurgById(String id) {
    return durgDao.findById(id).orElse(new Durg());
  }

  /**
   * 根据药品名查药品(模糊)
   */
  public List<Durg> findAllByName(String name){
    return durgDao.findAllByNameLike(name);
  }

  /**
   * 删除药品分类
   */
  public Response deletDurg(String id){
    try {
      durgDao.deleteById(id);
      return new Response(ResponseCode.CODE_200,MessageConstants.SUCCESS);
    } catch (Exception e){
      return new Response(ResponseCode.CODE_202,e.getMessage());
    }
  }
}
